package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.amqp.IotMsgBody;
import com.zzyl.nursing.amqp.IotMsgNotifyData;
import com.zzyl.nursing.amqp.IotMsgService;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 监测设备信息Service业务层处理
 *
 * @author laoYe
 * @date 2025-10-28
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询监测设备信息
     *
     * @param id 监测设备信息主键
     * @return 监测设备信息
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询监测设备信息列表
     *
     * @param deviceData 监测设备信息
     * @return 监测设备信息
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData) {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增监测设备信息
     *
     * @param deviceData 监测设备信息
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改监测设备信息
     *
     * @param deviceData 监测设备信息
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除监测设备信息
     *
     * @param ids 需要删除的监测设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除监测设备信息信息
     *
     * @param id 监测设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 批量插入监测设备信息
     *
     * @param iotMsgNotifyData
     */
    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        /*//判断设备是否存在
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if(device == null){
            //日志的记录，方便后期查找问题
            log.error("设备不存在：{}", iotId);
            return;
        }
        //获取到设备上报的数据，一个设备可以有多个service
        iotMsgNotifyData.getBody().getServices().forEach(s->{

            //所有数据都已经装入到map中
            Map<String, Object> properties = s.getProperties();
            if (ObjectUtil.isEmpty(properties)){
                return;
            }
            //处理上报时间日期
            LocalDateTime eventTime =  LocalDateTimeUtil.parse(s.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            //转入多个设备数据
            List<DeviceData> deviceDataList = new ArrayList<>();

            //遍历map集合，批量新增数据
            properties.forEach((key, value)->{
                DeviceData deviceData = DeviceData.builder()
                        .iotId(iotId)
                        .deviceName(device.getDeviceName())
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .functionId(key)
                        .accessLocation(device.getRemark())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .alarmTime(alarmTime)
                        .dataValue(value + "")
                        .build();
                deviceDataList.add(deviceData);

            });

            //批量保存
            saveBatch(deviceDataList);

        });


    }*/

        //1获取设备上的报的数据
        IotMsgBody body = iotMsgNotifyData.getBody();
        if (body != null) {
            //消息内容中的物模型数据
            List<IotMsgService> services = body.getServices();
            if (CollUtil.isNotEmpty(services)) {
                //才需要添加到数据库
                //检查设备是否存在，得到设备的iotId,在header中
                String iotId = iotMsgNotifyData.getHeader().getDeviceId();
                Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
                if (device != null) {
                    //存在设备
                    //有多少物模型属性就得遍历多少次
                    List<DeviceData> dataList = new ArrayList<>();
                    services.forEach(service -> {
                        String evenTime = service.getEventTime();
                        LocalDateTime alarmTime = LocalDateTimeUtil.parse(evenTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"))
                                .atZone(ZoneId.from(ZoneOffset.UTC))
                                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                                .toLocalDateTime();
                        //物模型数据
                        Map<String, Object> dataMap = service.getProperties();
                        dataMap.forEach((k, v) -> {
                            //4条记录，4个对象
                            DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                            //剔除创建时间、id、修改时间 、更新这、创建者
                            deviceData.setId(null);
                            deviceData.setCreateTime(null);
                            deviceData.setUpdateTime(null);
                            deviceData.setCreateBy(null);
                            deviceData.setAccessLocation(device.getRemark());

                            //根据物模型转成deviceData对象
                            deviceData.setFunctionId(k);
                            deviceData.setDataValue(String.valueOf(v));
                            deviceData.setAlarmTime(alarmTime);
                            dataList.add(deviceData);
                        });

                    });
                    if (CollUtil.isNotEmpty(dataList)) {
                        saveBatch(dataList);
                        //hash 结构来进行存储  大key  小key  value
                        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,iotId, JSONUtil.toJsonStr(dataList));
                    }
                }

            }
        }
    }

    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto) {
        //分页查询
        Page<DeviceData> page=Page.of(dto.getPageNum(),dto.getPageSize());
        //降序
        page.addOrder(OrderItem.desc("alarm_time"));

        //查询数据
        lambdaQuery().eq(StrUtil.isNotEmpty(dto.getDeviceId()),DeviceData::getIotId,dto.getDeviceId())
                .eq(StrUtil.isNotEmpty(dto.getFunctionId()),DeviceData::getFunctionId,dto.getFunctionId())
                .ge(Objects.nonNull(dto.getStartTime()),DeviceData::getAlarmTime,dto.getStartTime())
                .le(Objects.nonNull(dto.getEndTime()),DeviceData::getAlarmTime,dto.getEndTime())
                .page( page);
        //封装对象

        return new   TableDataInfo<DeviceData> (page.getTotal(), page.getRecords(), HttpStatus.SUCCESS, "查询成功");

    }
}
